package com.jiazhong.example.project.bookstore.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.example.project.bookstore.backend.service.BookService;
import com.jiazhong.example.project.bookstore.backend.service.DiscountService;
import com.jiazhong.example.project.bookstore.commons.bean.Book;
import com.jiazhong.example.project.bookstore.commons.bean.Discount;
import com.jiazhong.example.project.bookstore.commons.handler.BookSaveException;
import com.jiazhong.example.project.bookstore.commons.mapper.BookMapper;
import com.jiazhong.example.project.bookstore.commons.util.JsonResult;
import com.jiazhong.example.project.bookstore.commons.util.ResultTool;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Resource
    private BookMapper bookMapper;
    @Resource
    private DiscountService discountService;
    @Resource
    private HttpServletRequest request;

    @Cacheable(cacheNames = "book_find", key = "#page")
    public JsonResult find(int page) {
        IPage<Book> iPage = new Page<>(page, 10);
        List<Book> list = list(iPage);
        // 计算每本图书的折扣
        for (Book book : list) {
            JsonResult<Discount> discountByBookId = discountService.findDiscountByBookId(book.getId());
            if (discountByBookId.getSuccess()) {
                book.setDiscountRate(discountByBookId.getData().getDiscountRate());
                NumberFormat numberFormat = NumberFormat.getInstance();
                numberFormat.setMaximumFractionDigits(2);
                String format = numberFormat.format(discountByBookId.getData().getDiscountRate() * book.getPrice());
                book.setDiscountId(discountByBookId.getData().getId());
                book.setDiscountPrice(Double.parseDouble(format));
            } else {
                book.setDiscountRate(1.0);
                book.setDiscountPrice(book.getPrice());
            }
        }
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    @Cacheable(cacheNames = "book_findAll")
    public JsonResult findAll() {
        return ResultTool.success(list());
    }

    @Override
    public JsonResult saveBook(Book book, MultipartFile file) throws IOException {
        // 1. 上传图片
        String filePath = ResourceUtils.getURL("classpath:").getPath() + "/static/img";
        String originalFilename = file.getOriginalFilename();
        String type = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + type;
        File src = new File(filePath, fileName);
        file.transferTo(src);
        log.info("上传成功");
        // 2. 录入到数据库中
        // http://localhost:8000/img/??
        String sqlPath = "http://" + request.getServerName() + ":" + request.getServerPort() + "/img/";
        book.setImageName(sqlPath + fileName);
        boolean b = save(book);
        if (!b) {
            throw new BookSaveException("添加图书失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findBookByCategoryId(String categoryId) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        // queryWrapper.select("count(0)");
        Long count = bookMapper.selectCount(queryWrapper);
        if (count > 0) {
            return ResultTool.fail(201, "分类下有图书");
        }
        return ResultTool.success("success");
    }
}
